//: reusing/E18_FinalFields.java
/****************** Exercise6 18 *****************
 * Create a class with a static final field and a
 * final field and demonstrate the difference
 * between the two.
 ***********************************************/
package java_thinking.unit_7._7_8;

class SelfCounter {
  private static int count;
  private int id = count++;
  /**
    定义final时若未初始化，则要在构造函数中进行初始化
   *
   */
  private final String s;
  public SelfCounter(){
    //此处还不能应用s，因为s在此处还未进行初始化
    /*System.out.println(s);*/
    s = "ss";
    System.out.println(s);
  }
  public String toString() {
    System.out.println(count);
    System.out.println(s);
    return "SelfCounter " + id; }
}

class WithFinalFields {
  /**
   * 步骤2：当新建WithFinalFields对象时就会执行new SelfCounter()，此时SelfCounter.count还是为0
   * 而id此时是步骤1执行后的值，也就是1，执行完域初始化后count为2
   * 到toString方法时count已经是2了
   * scf对象指定为final后就无法再对这个对象引用地址进行修改，但是其内容可以修改
   */
  final SelfCounter scf = new SelfCounter();
  /**
   * 步骤1：内存加载时就创建了scsf对象，此时SelfCounter.count为0，不管new多少个对象都是0
   * 此时id也是0，因为count是动作以后才自加1
   */
  static final SelfCounter scsf = new SelfCounter();
  public String toString() {
    return "scf = " + scf + "\nscsf = " + scsf;
  }
}

public class E18_FinalFields {
  public static void main(String args[]) {
    System.out.println("First object:");
    System.out.println(new WithFinalFields());
    System.out.println("Second object:");
    System.out.println(new WithFinalFields());
  }
} /* Output:
First object:
scf = SelfCounter 1
scsf = SelfCounter 0
Second object:
scf = SelfCounter 2
scsf = SelfCounter 0
*///:~
